package de.reichelt.fx;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Pos;
import javafx.scene.control.TextField;

public class FxIntegerField extends TextField {
  private NumberFormat fmtN = new DecimalFormat("#,##0");
  
  public FxIntegerField() {
    this.setAlignment(Pos.BASELINE_RIGHT);
    this.textProperty().addListener(new ChangeListener<String>() {
      private boolean ignore;
      private int maxLength = 10;
      private String restrict = "-?\\d*";
      @Override
      public void changed(ObservableValue<? extends String> observableValue, String s, String s1) {
        if (ignore || s1 == null)
          return;
        if (maxLength > -1 && s1.length() > maxLength) {
          ignore = true;
          setText(s1.substring(0, maxLength));
          ignore = false;
        }
        if (!s1.matches(restrict)) {
          ignore = true;
          setText(s);
          ignore = false;
        }
      }
    });
  }
  
  public void setInteger(Integer d) {
    if (d==null) {
      this.setText("");
    } else {
      this.setText(d.toString().replace(".", ","));
    }
  }
  
  public Integer getInteger() {
    String txt = this.getText();
    if (txt==null || txt.isEmpty()) {
      return null;
    } else {
      txt = txt.replace(".", "").replace(",", ".");
      try {
        return Integer.parseInt(txt);
      } catch (NumberFormatException ex) {
        return null;
      }
    }
  }
  
  
}
